package com.hengtiansoft.lfy.db;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.hengtiansoft.lfy.db.been.InterpretRecordDB;
import com.hengtiansoft.lfy.db.been.OneMobileDB;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

/**
 * @ClassName: DatabaseHelper
 * @Description: 数据库帮助类
 * @author caijiajun <br/>
 * @date 2015年11月29日
 * 
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "lfy.db";
    private static final int DATABASE_VERSION = 5;
   private RuntimeExceptionDao<InterpretRecordDB, Integer> mInterpretRecordDao = null;
    private RuntimeExceptionDao<OneMobileDB, Integer> mOneMobileDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase,
            ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, InterpretRecordDB.class);
            TableUtils.createTable(connectionSource, OneMobileDB.class);
        } catch (Exception e) {
            Log.e(DatabaseHelper.class.getName(), "Can't create database", e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase,
            ConnectionSource connectionSource, int oldVer, int newVer) {

        try {
            Log.i(DatabaseHelper.class.getName(), "onUpgrade");
            // after we drop the old databases, we create the new ones
            TableUtils.dropTable(connectionSource, InterpretRecordDB.class,
                    true);
            TableUtils.dropTable(connectionSource, OneMobileDB.class, true);
            onCreate(sqLiteDatabase, connectionSource);

        } catch (SQLException e) {
            Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);
            throw new RuntimeException(e);
        }

    }

    @Override
    public void close() {
        super.close();
    }

    public RuntimeExceptionDao<InterpretRecordDB, Integer> getInterpretRecordDao() {
        if (mInterpretRecordDao == null)
            mInterpretRecordDao = getRuntimeExceptionDao(InterpretRecordDB.class);
        return mInterpretRecordDao;
    }

    public RuntimeExceptionDao<OneMobileDB, Integer> getOneMobileDao() {
        if (mOneMobileDao == null)
            mOneMobileDao = getRuntimeExceptionDao(OneMobileDB.class);
        return mOneMobileDao;
    }
}
